﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace M5.GeminiHybird.Core.Helper
{
    public class LocalStorageFileHelper
    {



        public static LocalStorageFileHelper Instance { get; } = new LocalStorageFileHelper();

        private Dictionary<string, string> _LocalStorageKeyValuePairs { get; set; } = new Dictionary<string, string>();

        private string _FilePath { get; } = Environment.CurrentDirectory + "/resource/localStorage.db";
        private LocalStorageFileHelper()
        {

            if (!File.Exists(_FilePath))
            {
                var fileStream =  File.Create(_FilePath);
                fileStream.Close();
            }

            StreamReader streamReader = new StreamReader(_FilePath);
            string line;
            string key;
            string value;
            string[] lineSplit;
            while (streamReader.Peek() > -1)
            {
                line = streamReader.ReadLine();
                lineSplit = line.Split('=');
                key = lineSplit[0];
                value = lineSplit[1];

                if (!_LocalStorageKeyValuePairs.ContainsKey(key))
                {
                    _LocalStorageKeyValuePairs.Add(key, value);
                }
            }
            streamReader.Close();
        }

        private void Save()
        {
            StreamWriter streamWriter = new StreamWriter(_FilePath);

            foreach (var item in _LocalStorageKeyValuePairs)
            {
                streamWriter.WriteLine($"{item.Key}={item.Value}");
            }
            streamWriter.Flush();
            streamWriter.Close();
        }

        public void RemoveItem(string key)
        {
            if (!_LocalStorageKeyValuePairs.ContainsKey(key))
                return;

            _LocalStorageKeyValuePairs.Remove(key);
            Save();
        }


        public void SetItem(string key, string value)
        {
            if (_LocalStorageKeyValuePairs.ContainsKey(key))
                _LocalStorageKeyValuePairs[key] = value;
            else
                _LocalStorageKeyValuePairs.Add(key, value);

            Save();
        }

        public string GetItem(string key)
        {
            if (!_LocalStorageKeyValuePairs.ContainsKey(key))
                return "";

            return _LocalStorageKeyValuePairs[key];
        }
    }
}
